﻿// ———————————————————————–
// <copyright file="ValueListMessageFilter.cs" company="The MITRE Corporation">
//    Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// ———————————————————————–
/////////////////////////////////////////////////////////////////////////////////////////////////
// ValueListMessageFilter.cs - "Methods For Filtering ValueLists"
// Project: "IC.NETSOA"- "ICNETCoreRouter"
//
// Language:    C#, .NET 4.0
// Platform:    Windows 7, VS 2010
// Author:      Don McGarry The MITRE Corporation
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)
                
using System;
using System.Linq;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Xml.Linq;
using EDXLSharp;
using ICNETServices;

namespace ICNETCoreRouter
{
  /// <summary>
  /// Contains methods for filtering ValueListMessages
  /// </summary>
  public class ValueListMessageFilter : MessageFilter
  {
    /// <summary>
    /// The fields contained within the ValueList which are used as filters.
    /// </summary>
    private string listname, listuri, value;

    /// <summary>
    /// The namespaces for EDXLDE, the value list pased in, and serialized arrays. 
    /// </summary>
    private XNamespace denamespace, commontypesnamespace, arraynamespace;

    /// <summary>
    /// Initializes a new instance of the ValueListMessageFilter class.
    /// </summary>
    /// <param name="filterData">The data used to construct the filter.</param>
    public ValueListMessageFilter(string filterData)
    {
      if (string.IsNullOrEmpty(filterData))
      {
        throw new ArgumentNullException("filterData can't be null or empty");
      }

      string[] split;
      char[] separator = new char[] { ';' };
      split = filterData.Split(separator);
      if (split.Count() != 3)
      {
        throw new ArgumentException("Filter Data Must Be a ';' delimited string with three elements");
      }
      else
      {
        this.listname = split[0];
        this.listuri = split[1];
        this.value = split[2];
        this.denamespace = EDXLConstants.EDXLDE10Namespace;
        this.commontypesnamespace = EDXLConstants.EDXLDE10Namespace;
        this.arraynamespace = ICNETSOAConstants.ArraySerializedNamespace;
      }
    }

    /// <summary>
    /// Attempts to match a message using the initially given filter criteria. 
    /// </summary>
    /// <remarks>Must be overriden. </remarks>
    /// <param name="message">The message to be matched.</param>
    /// <returns>false if the message did not match up against the filter data, true if it did.</returns>
    public override bool Match(Message message)
    {
      return false;
    }

    /// <summary>
    /// Matches a MessageBuffer against the intitially given filter criteria. 
    /// </summary>
    /// <remarks>Must be overriden.</remarks>
    /// <param name="buffer">The MessageBuffer to be matched.</param>
    /// <returns>True if the MessageBuffer was matched, false if it was not.</returns>
    public override bool Match(MessageBuffer buffer)
    {
      XElement xe;
      xe = buffer.CreateMessage().GetBody<XElement>();
      var valuelistlinq =
          from el in xe.Descendants(this.denamespace + this.listname)
          select el;

      if (valuelistlinq.Count() == 0)
      {
        return false;
      }
      else
      {
        bool isMatch = false;

        foreach (XElement valuelist in valuelistlinq)
        {
          // XElement valuelist = valuelistlinq.First();
          var valuelisturnlinq =
            from el in valuelist.Descendants(this.commontypesnamespace + "valueListUrn")
            where el.Value == this.listuri             ////select el.AncestorsAndSelf("value");
            select el.Parent.Descendants(this.commontypesnamespace + "value");
          var values =
            from el in valuelistlinq.DescendantsAndSelf(this.commontypesnamespace + "value")
            where el.Value == this.value
            select el;
          int i = values.Count();
          if (i > 0)
          {
            isMatch = true;
            break;
          }
        }

        /* else if (valuelistlinq.Count() > 1)
           {
                throw new ArgumentException("Multiple Lists Found!");
            }*/

        return isMatch;
      }
    }
  }
}
